package com.castile.secondkill.service.impl;

import com.castile.secondkill.dao.PromoDOMapper;
import com.castile.secondkill.dataobject.PromoDO;
import com.castile.secondkill.service.PromoService;
import com.castile.secondkill.service.model.PromoModel;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 秒杀服务实现
 *
 * @author Hongliang Zhu
 * @create 2023-03-18 23:15
 */
@Service
public class PromoServiceImpl implements PromoService {
    @Autowired
    private PromoDOMapper promoDOMapper;

    @Override
    public PromoModel getPromoByItemId(Integer itemId) {
        PromoDO promoDO = promoDOMapper.selectByItemId(itemId);
        // 判断
        if (promoDO == null) {
            return null;
        }
        // dataobject-- >  model
        PromoModel promoModel = convertFromDataObject(promoDO);
        // 判断当前时间是否秒杀活动即将开始或者正在进行
        if (promoModel.getStartDate().isAfterNow()) {
            // 秒杀还未开始
            promoModel.setStatus(1);
        } else if (promoModel.getEndDate().isBeforeNow()) {
            // 秒杀已经结束
            promoModel.setStatus(3);

        } else {
            // 秒杀正在进行中
            promoModel.setStatus(2);
        }

        return promoModel;


    }
    private PromoModel convertFromDataObject(PromoDO promoDO){
        if(promoDO == null){
            return null;
        }
        PromoModel promoModel = new PromoModel();
        BeanUtils.copyProperties(promoDO, promoModel);
        promoModel.setPromoItemPrice(new BigDecimal(promoDO.getPromoItemPrice()));
        promoModel.setStartDate(new DateTime(promoDO.getStartDate()));
        promoModel.setEndDate(new DateTime(promoDO.getEndDate()));
        return promoModel;
    }
}
